using Acme.ELeMe.SDK.Request;
using Acme.ELeMe.SDK.Tools;
using NETCore.Encrypt;
using Newtonsoft.Json;
using WebApiClientCore;

namespace Acme.ELeMe.SDK.Api;

public class ElmSign : IApiParameter
{
    public ElmSign(string cmd)
    {
        Cmd = cmd;
    }

    public string Cmd { get; set; }

    public string AppId { get; set; }

    public string AppSecret { get; set; }

    public string Version { get; set; } = "3";


    public Task OnRequestAsync(ApiParameterContext context)
    {
        var dictionary = context.ParameterValue.ToDictionary();

        dictionary.Remove("AppId");
        dictionary.Remove("AppSecret");
        dictionary.Remove("Cmd");
        dictionary.Remove("Version");

        var bodyString = JsonConvert.SerializeObject(dictionary);
        var baseRequest = new BaseRequest
        {
            cmd = Cmd,
            source = AppId,
            version = Version,
            body = bodyString,
            ticket = Guid.NewGuid().ToString().ToUpper(),
            timestamp = DateTimeOffset.Now.ToUnixTimeSeconds().ToString(),
            encrypt = "aes"
        };

        baseRequest.sign = GetSign(baseRequest, AppSecret);
        var encodedContent = new FormUrlEncodedContent(baseRequest.ToNameValueCollection());
        context.HttpContext.RequestMessage.Content = encodedContent;
        return Task.CompletedTask;
    }

    private static string GetSign(BaseRequest model, string appSecret)
    {
        var sign = "";
        var preSignDic = model.ToDictionary<string>();
        preSignDic.Add("secret", appSecret);
        preSignDic.Remove("Sign");
        var preSignStr = Common.SortParamsByAscll(preSignDic);
        sign = EncryptProvider.Md5(preSignStr).ToUpper();
        return sign;
    }
}